package mvp.levelup.web.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * User: valera
 * Date: 5/3/14
 * Time: 11:41 AM
 */
@WebServlet("/test")
public class TestServlet extends HttpServlet {
    private static final Logger log = LoggerFactory.getLogger(TestServlet.class);

    public void init() {
        log.error("Test Servlet Inited");
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        countExec(req);
        StringBuilder toSend = new StringBuilder();
        Map<String, String[]> paramMap = req.getParameterMap();
        String addr = req.getRemoteAddr();
        String ua = req.getHeader("User-Agent");
        toSend.append("IP: ").append(addr).append("<br/>")
                .append("UA: ").append(ua).append("<br/>");
        Iterator<Map.Entry<String, String[]>> iter = paramMap.entrySet().iterator();
        Map.Entry<String, String[]> tmp;
        while (iter.hasNext()) {
            tmp = iter.next();
            toSend.append(tmp.getKey()).append(": ");
            for (int i = 0; i < tmp.getValue().length; i++) {
                toSend.append(tmp.getValue()[i]).append(",");
            }
            toSend.deleteCharAt(toSend.length() - 1);
            toSend.append("<br/>");
        }
        AtomicInteger counter = (AtomicInteger) req.getServletContext().getAttribute("counter");
        int value = counter.intValue();
        toSend.append("Req count: " + value);
        toSend.append("<br/>");
        String f1res = (String) req.getAttribute("filter1");
        String f2res = (String) req.getAttribute("filter2");
        toSend.append("Filter1: ").append(f1res);
        toSend.append("<br/>");
        toSend.append("Filter2: ").append(f2res);
        toSend.append("<hr/>");
        try {
            PrintWriter pw = resp.getWriter();
            pw.println(toSend.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void countExec(HttpServletRequest req) {
        AtomicInteger counter = (AtomicInteger) req.getServletContext().getAttribute("counter");
        if (counter == null) {
            synchronized (this) {
                counter = (AtomicInteger) req.getServletContext().getAttribute("counter");
                if (counter == null) {
                    counter = new AtomicInteger(0);
                    req.getServletContext().setAttribute("counter", counter);
                }
            }
        }
        counter.incrementAndGet();
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        try {
            InputStream is = req.getInputStream();
            Scanner sc = new Scanner(is);
            StringBuilder data = new StringBuilder();
            while (sc.hasNextLine()) {
                data.append(sc.nextLine());
            }
            String respStr = "YOUR DATA: " + data.toString();
            PrintWriter pw = resp.getWriter();
            pw.println(respStr);
            log.error(respStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
